<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>unitManager</title>
    <!-- Bootstrap -->
    <link rel="stylesheet" href="../commons/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <!-- 加载bootstrap-select -->
    <link href="../commons/bootstrap-select-1.13.9-dist/css/bootstrap-select.min.css" rel="stylesheet">
    <!-- 加载bootstrap-treeview -->
    <link href="../commons/bootstrap-treeview-1.2.0-dist/bootstrap-treeview.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../commons/css/currency.css">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-collapse">
                <span class="sr-only">切换导航</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">CIMS-校园即时通讯系统</a>
        </div>
        <div class="collapse navbar-collapse" id="example-navbar-collapse">
            <ul class="nav navbar-nav navbar-left">
                <li class="active"><a href="unitIndex"> 首页</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false"> 单位管理<span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="unitTypeManager"> 单位类型</a></li>
                        <li><a href="unitManager"> 单位设置</a></li>
                    </ul>
                </li>
                <li><a href="userManager"> 用户管理</a></li>
            </ul>
            <ul class="nav navbar-nav" style="float: right">
                <li class=""><a id="loginUser_nav">管理员：</a></li>
                <li class=""><a id="logout_nav">注销</a></li>
            </ul>
        </div>
    </div>
</nav>

<div class="container">
    <h3 class="page-header">单位管理</h3>
    <div class="row">
        <div class="col-md-5">
            <div class="col-md-3">
                <p>单位类型：</p>
            </div>
            <div class="col-md-9">
                <select class="selectpicker form-control" title="请选择单位类型" id="unitType_search_select">
                </select>
            </div>
        </div>
        <div class="col-md-5">
            <div class="col-md-3">
                <p>单位名称：</p>
            </div>
            <div class="col-md-9">
                <input type="text" class="form-control" placeholder="请输入单位名称" id="unitName_search_input">
            </div>
        </div>
        <div class="col-md-2">
            <div class="input-group">
                    <span class="input-group-btn">
                        <button class="btn btn-primary" id="search_btn"><span class="glyphicon glyphicon-search"></span>
                            搜索</button>
                        <button class="btn btn-warning" id="reset_btn"><span class="glyphicon glyphicon-refresh"></span>
                            重置</button>
                    </span>
            </div>
        </div>
    </div>
    <h5 class="page-header"></h5>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-bordered table-striped table-hover" id="units-table">
                <thead>
                <tr>
                    <th><input type="checkbox" id="check_all"></th>
                    <th>单位名称</th>
                    <th>单位类型</th>
                    <th>排序号</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
                <tfoot>
                </tfoot>
            </table>
        </div>
        <div class="col-md-1"></div>
    </div>
</div>


<div class="modal fade" id="unit_add_modal" tabindex="-1" role="dialog" aria-labelledby="unit_add_modal"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title"> 新增单位</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form" id="unit_add_frm">
                    <div class="form-group">
                        <label for="unitName_add_modal" class="col-sm-3 control-label"> 单位名称：</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" name="unitName" id="unitName_add_modal"
                                   placeholder="请输入单位名称">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label"> 单位类型：</label>
                        <div class="col-sm-9">
                            <select class="selectpicker form-control" name="unitTypeId" title="请选择单位类型"
                                    id="unitTypeSelect_add_modal">
                            </select>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="unitSortNum_add_modal" class="col-sm-3 control-label"> 排序号：</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" name="unitSortNum" id="unitSortNum_add_modal"
                                   placeholder="请输入排序号">
                            <span class="help-block"></span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"> 关闭</button>
                <button type="button" class="btn btn-primary" id="unit_save_btn"> 保存</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="unit_modify_modal" tabindex="-1" role="dialog" aria-labelledby="unit_modify_modal"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title"> 修改单位</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form" id="unit_modify_frm">
                    <div class="form-group">
                        <label for="unitName_modify_modal" class="col-sm-3 control-label"> 单位名称：</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" name="unitName" id="unitName_modify_modal"
                                   placeholder="请输入单位名称">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label"> 单位类型：</label>
                        <div class="col-sm-9">
                            <select class="selectpicker form-control" name="unitTypeId" title="请选择单位类型"
                                    id="unitTypeSelect_modify_modal">
                            </select>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="unitSortNum_modify_modal" class="col-sm-3 control-label"> 排序号：</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" name="unitSortNum" id="unitSortNum_modify_modal"
                                   placeholder="请输入排序号">
                            <span class="help-block"></span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"> 关闭</button>
                <button type="button" class="btn btn-primary" id="unit_modify_btn"> 保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 批量导入模态框 -->
<div class="modal fade" id="unit_import_modal" tabindex="-1" role="dialog" aria-labelledby="unit_import_modal"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title"> 批量导入</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form" id="unit_import_frm" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="unitFile_import_modal" class="col-sm-3 control-label"> 上传附件：</label>
                        <div class="col-sm-9">
                            <input type="file" id="unitFile_import_modal" name="unitFile">
                            <p class="help-block">文件类型限定为CSV文件，大小不能超过2M;</p>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-12">
                            <div class="progress progress-striped active" id="progress_import_frm"
                                 style="display: none;">
                                <div class="progress-bar progress-bar-success" role="progressbar" aria-valuemax="100"
                                     style="width: 100%;"
                                     id="progressBar_import_frm"><span>正在上传文件...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"> 关闭</button>
                <button type="button" class="btn btn-primary" id="unitFile_import_btn"> 导入</button>
            </div>
        </div>
    </div>
</div>


<div class="footer ">
    <div class="container">
        <div class="row footer-bottom">
            <ul class="list-inline text-center">
                <li> Campus Instant Messaging System @2020 杭州职业技术学院 软件技术专业</li>
            </ul>
        </div>
    </div>
</div>
</div>

<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
<script src="../commons/js/jquery.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="../commons/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script src="../commons/bootstrap-treeview-1.2.0-dist/bootstrap-treeview.min.js"></script>
<script src="../commons/bootstrap-select-1.13.9-dist/js/bootstrap-select.min.js"></script>
<script src="../commons/js/login.js"></script>
<script type="text/javascript">
    var pn = 1;
    var unitTypeId, unitName;

    $(function () {
        getUnitTypeList("#unitType_search_select", "全部类型", "");
        to_page(pn);
    });

    function to_page(pn) {
        $.ajax({
            url: "units",
            type: "GET",
            data: {"unitTypeId": unitTypeId, "unitName": unitName, "pn": pn},
            dataType: "json",
            beforeSend: function () {
                $("#units-table tbody").empty();
                $("#units-table tfoot").empty();
                $("#units-table tbody").append("<tr><td colspan='6'>正在加载数据，请稍后...</td></tr>");
            },
            success: function (result) {
                if (result.code == 100) {
                    //1、显示院校管理员信息
                    build_units_table(result);
                    //2、显示分页信息
                    build_page_nav(result);
                } else {

                }
            },
            error: function () {
                $("#units-table tbody").empty();
                $("#units-table tfoot").empty();
                $("#units-table tbody").append("<tr><td colspan='5'>查询出错，请稍后再试！</td></tr>");
            }
        });
    }

    function build_units_table(result) {
        $("#units-table tbody").empty();
        var units = result.extend.pageInfo.list;
        $.each(units, function (index, unit) {
            var chkTd = $("<td></td>").addClass("tdCenter").append($("<input>").addClass("check_item").attr({"type": "checkbox"}));
            var unitNameTd = $("<td></td>").append(unit.unitName);
            var unitTypeTd = $("<td></td>").append(unit.unitType.unitTypeName);
            var unitSortNumTd = $("<td></td>").addClass("tdCenter").append(unit.unitSortNum);
            var editBtn = $("<button></button>").addClass("btn btn-sm btn-primary edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-edit")).append(" 修改");
            editBtn.attr({"edit-id": unit.id, "pn": result.extend.pageInfo.pageNum});
            var delBtn = $("<button></button>").addClass("btn btn-sm btn-danger delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-remove")).append(" 删除");
            delBtn.attr("delete-id", unit.id);
            var unitOperationDiv = $("<div></div>").addClass("input-group").append($("<span></span>").addClass("input-group-btn").append(editBtn).append(delBtn));
            var unitOperationTd = $("<td></td>").addClass("tdCenter").append(unitOperationDiv);

            $("<tr></tr>").append(chkTd)
                .append(unitNameTd)
                .append(unitTypeTd)
                .append(unitSortNumTd)
                .append(unitOperationTd)
                .appendTo("#units-table tbody");
        });
    }

    function build_page_nav(result) {
        $("#units-table tfoot").empty();
        var operatorUl = $("<ul></ul>").addClass("pagination pull-left").attr("style", "margin: 0 0 0 0;");
        var addLi = $("<li></li>").append($("<a></a>").attr("id", "unit_add_btn").append($("<span></span>").addClass("glyphicon glyphicon-plus").append("新增")));
        var removeLi = $("<li></li>").append($("<a></a>").attr("id", "unit_delete_all_btn").append($("<span></span>").addClass("glyphicon glyphicon-remove").append("批量删除")));
        var importLi = $("<li></li>").append($("<a></a>").attr("id", "unit_import_btn").append($("<span></span>").addClass("glyphicon glyphicon-upload").append("批量导入")));
        operatorUl.append(addLi).append(removeLi).append(importLi);

        var pageUl = $("<ul></ul>").addClass("pagination").attr("style", "margin: 0 0 0 0;");
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页"));
        if (result.extend.pageInfo.isFirstPage) {
            firstPageLi.addClass("disabled");
        } else {
            firstPageLi.click(function () {
                to_page(1);
            });
        }
        pageUl.append(firstPageLi);

        var previousPageLi = $("<li></li>").append($("<a></a>").append("《"));
        if (result.extend.pageInfo.hasPreviousPage) {
            previousPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum - 1);
            });
        } else {
            previousPageLi.addClass("disabled");
        }
        pageUl.append(previousPageLi);
        $.each(result.extend.pageInfo.navigatepageNums, function (index, npNum) {
            var pageLi = $("<li></li>").append($("<a></a>").append(npNum));
            if (result.extend.pageInfo.pageNum == npNum) {
                pageLi.addClass("active");
            } else {
                pageLi.click(function () {
                    to_page(npNum);
                });
            }
            pageUl.append(pageLi);
        });
        var nextPageLi = $("<li></li>").append($("<a></a>").append("》"));
        if (result.extend.pageInfo.hasNextPage) {
            nextPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum + 1);
            });
        } else {
            nextPageLi.addClass("disabled");
        }
        pageUl.append(nextPageLi);
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页"));
        if (result.extend.pageInfo.isLastPage) {
            lastPageLi.addClass("disabled");
        } else {
            lastPageLi.click(function () {
                to_page(result.extend.pageInfo.pages);
            });
        }
        pageUl.append(lastPageLi);

        var pageInfoUl = $("<ul></ul>").addClass("pagination pull-right").attr("style", "margin: 0 0 0 0;");
        var pageInfoLi = $("<li></li>").addClass("disabled").append($("<a></a>").attr("style", "border: 0px").append("当前第 " + result.extend.pageInfo.pageNum + " 页，总 "
            + result.extend.pageInfo.pages + " 页，总 "
            + result.extend.pageInfo.total + " 条记录"));
        pageInfoUl.append(pageInfoLi);

        pn = result.extend.pageInfo.pageNum;

        var pageNavTd = $("<td></td>").addClass("text-center")
            .attr({"colspan": 5}).append(operatorUl).append(pageUl).append(pageInfoUl);

        $("<tr></tr>").append(pageNavTd)
            .appendTo("#units-table tfoot");
    }

    $(document).on("click", ".delete_btn", function () {
        var unitName = $(this).parents("tr").find("td:eq(1)").text();
        if (confirm("确认删除[ " + unitName + " ]吗？")) {
            $.ajax({
                url: "unit/" + $(this).attr("delete-id"),
                type: "DELETE",
                dataType: "json",
                success: function (result) {
                    alert(result.msg);
                    if (result.code = 100) {
                        //删除成功
                        //刷新单位列表显示
                        to_page(1);
                        $("#check_all").prop("checked", false);
                    }
                }
            });
        }
    });

    $("#check_all").click(function () {
        $(".check_item").prop("checked", $(this).prop("checked"));
    });

    $(document).on("click", ".check_item", function () {
        var flag = $(".check_item").length == $(".check_item:checked").length;
        $("#check_all").prop("checked", flag);
    });

    $(document).on("click", "#unit_delete_all_btn", function () {
        var unitNames = "", ids = "";
        $.each($(".check_item:checked"), function () {
            unitNames = unitNames + $(this).parents("tr").find("td:eq(1)").text() + ",";
            ids = ids + $(this).parents("tr").find("td:eq(4)").find(".delete_btn").attr("delete-id") + "-";
        });
        unitNames = unitNames.substring(0, unitNames.length - 1);
        ids = ids.substring(0, ids.length - 1);
        if (confirm("确认删除[ " + unitNames + " ]吗？")) {
            $.ajax({
                url: "unit/" + ids,
                type: "DELETE",
                dataType: "json",
                success: function (result) {
                    alert(result.msg);
                    if (result.code = 100) {
                        //删除成功
                        //刷新单位列表显示
                        to_page(1);
                        $("#check_all").prop("checked", false);
                    }
                }
            });
        }
    });

    function getUnitTypeList(element, txt, selText) {
        $.ajax({
            url: "unitTypes",
            type: "GET",
            dataType: "json",
            success: function (result) {
                $(element).empty();
                if (txt != "") {
                    optionElement = $("<option></option>").append(txt).attr({"value": 0});
                    optionElement.appendTo($(element));
                }
                $.each(result.extend.unitTypes, function (index, unitType) {
                    optionElement = $("<option></option>").append(unitType.unitTypeName).attr({"value": unitType.id});
                    optionElement.appendTo($(element));
                });
                $(element).removeAttr("disabled");
                $(element).selectpicker("refresh");
                if (selText != "") {
                    $(element).next().prop("title", selText);
                    $(element).next().find("div.filter-option-inner-inner").html(selText);
                    $(element).next().removeClass("bs-placeholder");
                }
            }
        });
    }

    $("#reset_btn").click(function () {
        getUnitTypeList("#unitType_search_select", "全部类型", "");
        $("#unitName_search_input").val("");
    });

    $("#search_btn").click(function () {
        if ($("#unitType_search_select").val() == "") {
            unitTypeId = 0;
        } else {
            unitTypeId = $("#unitType_search_select").val();
        }
        unitName = $("#unitName_search_input").val();
        to_page(pn);
    });

    $(document).on("click", "#unit_add_btn", function () {
        getUnitTypeList("#unitTypeSelect_add_modal", "", "");
        $("#unit_add_modal").modal({
            "backdrop": "static"
        });
    });

    $(document).on('hidden.bs.modal', '.modal', function () {
        $("#unit_add_modal form")[0].reset();
        $("#unit_add_modal form").find("*").removeClass("has-error has-success");
        $("#unit_add_modal form").find(".help-block").text("");

        $("#unit_modify_modal form")[0].reset();
        $("#unit_modify_modal form").find("*").removeClass("has-error has-success");
        $("#unit_modify_modal form").find(".help-block").text("");

        $("#unit_import_modal form")[0].reset();
        $("#unit_import_modal form").find("*").removeClass("has-error has-success");
        $("#unit_import_modal form").find(".help-block").text("");

        $(".modal .selectpicker").empty();
        $(".modal .selectpicker").attr("disabled", "disabled");
        $(".modal .selectpicker").selectpicker("refresh");

        $("#progress_import_frm").hide();
    });

    $("#unit_save_btn").click(function () {
        //数据校验

        //新增院校管理员的异步请求
        $.ajax({
            url: "unit",
            data: $("#unit_add_frm").serialize(),
            type: "post",
            dataType: "json",
            success: function (result) {
                if (result.code == 100) {
                    //添加成功，刷新所有地域信息
                    $("#unit_add_modal").modal('hide');
                    alert("单位信息添加成功！");
                    to_page(1);
                    $("#check_all").prop("checked", false);
                }
            }
        });
    });

    $(document).on("click", ".edit_btn", function () {
        $.ajax({
            url: "unit",
            data: {"id": $(this).attr("edit-id")},
            type: "GET",
            dataType: "json",
            success: function (result) {
                if (result.code == 100) {
                    $("#unitName_modify_modal").val(result.extend.unit.unitName);
                    getUnitTypeList("#unitTypeSelect_modify_modal", "", result.extend.unit.unitType.unitTypeName);
                    $("#unitSortNum_modify_modal").val(result.extend.unit.unitSortNum);
                }
            }
        });
        $("#unit_modify_btn").attr("edit-id", $(this).attr("edit-id"));
        $("#unit_modify_modal").modal({
            "backdrop": "static"
        });
    });

    $("#unit_modify_btn").click(function () {
        //数据校验

        //新增院校管理员的异步请求
        $.ajax({
            url: "unit/" + $(this).attr("edit-id"),
            data: $("#unit_modify_frm").serialize(),
            type: "put",
            dataType: "json",
            success: function (result) {
                if (result.code == 100) {
                    //修改成功，刷新所有地域信息
                    $("#unit_modify_modal").modal('hide');
                    alert("单位信息修改成功！");
                    to_page(1);
                    $("#check_all").prop("checked", false);
                }
            }
        });
    });

    $(document).on("click", "#unit_import_btn", function () {
        $("#unit_import_modal").modal({
            "backdrop": "static"
        });
    });

    $("#unitFile_import_btn").click(function () {
        $("#progress_import_frm").show();

        var formData = new FormData($('#unit_import_frm')[0]);
        $.ajax({
            url: "fileImport",
            type: "POST",
            data: formData,
            dataType: "json", //返回数据的类型
            async: false,
            cache: false,
            contentType: false, //发送数据的类型
            processData: false,
            success: function (result) {
                if (result.code == 100) {
                    alert("上传成功");
                    $("#unit_import_modal").modal('hide');
                    alert("批量导入成功！");
                    to_page(1);
                    $("#check_all").prop("checked", false);
                }
            },
            error: function () {
                alert("上传失败");
            }
        });
    });
</script>
</body>
</html>
